<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    #myCanvas{
        margin:auto;
        /*border:1px solid;*/
        box-shadow: 0 0 10px #999;
    }
</style>
<body>
<canvas id="myCanvas" height="500" width="800">

</canvas>


</body>


<script>
    var canvas = document.getElementById("myCanvas");
    var card = document.getElementById("card");
    if(!canvas.getContext){
        alert("浏览器不支持");
    }
    var txt = canvas.getContext("2d");
    function DrawPan(x,y,width,height,color) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.color = color;
    }

    DrawPan.prototype.draw = function(){
        txt.beginPath();
        txt.fillStyle = this.color;
        txt.fillRect(this.x,this.y,this.width,this.height);
        // txt.strokeRect(10,10,100,100)
    };

    function CreateSqu() {
        var arr = [];
        var x = 10;
        var y = 10;
        for(var i = 0; i < 4; i ++){
            for(var j = 0; j < 4; j ++){
                var squ = new DrawPan(x,y,100,100,"gray");
                squ.draw();
                x += 110;
            }
            x = 10;
            y += 110;
            // var rect = new DrawPan(x,y,100,100,'#999');
            // arr.push(rect);
            // x -= 20
        }

        // this.body = new Array();
        // var x = this.head.x - 20;
        // var y = this.head.y;
        // for(var i = 0; i < 3; i ++){
        //     var rect = new Rect(x,y,20,20,'#999');
        //     this.body.push(rect);
        //     x -= 20
        // }
    }
    CreateSqu()
    var create = new CreateSqu();
    canvas.onclick = function(e){
        e=e||event;//获取事件对象
        //获取事件在canvas中发生的位置
        var x=e.clientX-canvas.offsetLeft;
        var y=e.clientY-canvas.offsetTop;
        //如果事件位置在矩形区域中
        console.log(x,y);

        // x + 10    x+10+100+10
        //y+10  y+10+100+10
        //10*x+100*(x-1)=this.x  水平第几个
        //10*y+100*(y-1)=this.y  垂直第几个
        //x=10+this.x/110
        console.log(Math.floor(x/110));
        console.log(create.x);
        var fX = Math.floor(x/110)*100+10*(Math.floor(x/110)+1);
        var fY = Math.floor(y/110)*100+10*(Math.floor(y/110)+1);
        console.log(fX,fY);
        angle=0;
        //清除画布
        // txt.clearRect(0, 0, canvas.width, canvas.height);
        //设置原点
        // txt.translate(fX, fY);
        //旋转角度
        // txt.rotate(0);
        //设置填充颜色
        txt.fillStyle = "#dff";
        //绘制矩形
        txt.fillRect(fX, fY, 100, 100);
        // angle += 0.05 * Math.PI;
        // if(x>=rect.x&&x<=rect.x+rect.w&&y>=rect.y&&y<=rect.y+rect.h){
        //     window.open('链接地址');//打开指定链接
        // }
    }


</script>
</html>
